﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SubSonic;
using ExtAspNet;


namespace TCMSystem.admin
{
    public partial class role_user : PageBase
    {
        private static readonly log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        #region Module

        /// <summary>
        /// 当前页面所属的模块
        /// </summary>
        public override ModuleType Module
        {
            get
            {
                return ModuleType.CoreRoleUser;
            }
        }

        #endregion

        #region Page_Load

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadData();
            }
        }

        private void LoadData()
        {
            // 权限检查
            CheckPowerNewWithButton(btnNew);
            CheckPowerDeleteWithButton(btnDeleteSelected);


            ResolveDeleteButtonForGrid(btnDeleteSelected, Grid2, "确定要从当前角色中移除选中的{0}项记录吗？");

            // 每页记录数
            Grid1.PageSize = TblMstConfigHelper.PageSize;
            BindGrid();
            // 默认选中第一个角色
            Grid1.SelectedRowIndexArray = new int[] { 0 };

            // 每页记录数
            Grid2.PageSize = TblMstConfigHelper.PageSize;
            BindGrid2();
        }

        private void BindGrid()
        {
            SqlQuery q = new Select().From<TblMstRole>();
            q.Where("1").IsEqualTo("1");

            // 排列
            q.OrderBys.Add(GetSortExpression(Grid1, TblMstRole.Schema));

            TblMstRoleCollection items = q.ExecuteAsCollection<TblMstRoleCollection>();

            Grid1.DataSource = items;
            Grid1.DataBind();
        }

        private void BindGrid2()
        {
            TblMstUserCollection items;

            if (Grid1.SelectedRowIndexArray.Length != 0)
            {
                SqlQuery q = new Select().From<TblMstUser>();
                q.Where("1").IsEqualTo("1");

                // 在职务名称中搜索
                string searchText = ttbSearchUser.Text.Trim();
                if (!String.IsNullOrEmpty(searchText))
                {
                    q.And(TblMstUser.NameColumn).ContainsString(searchText);
                }

                // 过滤选中角色下的所有用户
                object[] values = Grid1.DataKeys[Grid1.SelectedRowIndexArray[0]];
                int roleId = Convert.ToInt32(values[0]);
                q.And(TblMstUser.RoleIdColumn).IsEqualTo(roleId);


                // 在查询添加之后，排序和分页之前获取总记录数
                // Grid1总共有多少条记录
                Grid2.RecordCount = q.GetRecordCount();

                // 排列
                q.OrderBys.Add(GetSortExpression(Grid2, TblMstUser.Schema));

                // 数据库分页
                q.Paged(Grid2.PageIndex + 1, Grid2.PageSize);
                items = q.ExecuteAsCollection<TblMstUserCollection>();
            }
            else
            {
                Grid2.RecordCount = 0;
                items = new TblMstUserCollection();
            }

            Grid2.DataSource = items;
            Grid2.DataBind();
        }

        #endregion

        #region Grid1 Events

        protected void Grid1_Sort(object sender, GridSortEventArgs e)
        {
            Grid1.SortColumnIndex = e.ColumnIndex;
            BindGrid();

            // 默认选中第一个角色
            Grid1.SelectedRowIndexArray = new int[] { 0 };

            BindGrid2();
        }

        protected void Grid1_RowClick(object sender, ExtAspNet.GridRowClickEventArgs e)
        {
            BindGrid2();
        }

        #endregion

        #region Grid2 Events

        protected void ttbSearchUser_Trigger2Click(object sender, EventArgs e)
        {
            ttbSearchUser.ShowTrigger1 = true;
            BindGrid2();
        }

        protected void ttbSearchUser_Trigger1Click(object sender, EventArgs e)
        {
            ttbSearchUser.Text = String.Empty;
            ttbSearchUser.ShowTrigger1 = false;
            BindGrid2();
        }

        protected void Grid2_PreDataBound(object sender, EventArgs e)
        {
            // 数据绑定之前，进行权限检查
            CheckPowerDeleteWithLinkButtonField(Grid2, "deleteField");
        }

        protected void Grid2_Sort(object sender, GridSortEventArgs e)
        {
            Grid2.SortColumnIndex = e.ColumnIndex;
            BindGrid2();
        }

        protected void Grid2_PageIndexChange(object sender, GridPageEventArgs e)
        {
            Grid2.PageIndex = e.NewPageIndex;
            BindGrid2();
        }

        protected void btnDeleteSelected_Click(object sender, EventArgs e)
        {
            // 在操作之前进行权限检查
            if (!CheckPowerDelete())
            {
                CheckPowerFailWithAlert();
                return;
            }

            // 从每个选中的行中获取ID（在Grid1中定义的DataKeyNames）
            List<int> ids = GetSelectedDataKeyIDs(Grid2);

            // 执行数据库操作
            TblMstUserCollection users = new Select().From<TblMstUser>()
                .Where(TblMstUser.IdColumn).In(ids)
                .ExecuteAsCollection<TblMstUserCollection>();
            foreach (TblMstUser user in users)
            {
                user.RoleId = null;
            }
            users.BatchSave();


            // 清空当前选中的项
            Grid2.SelectedRowIndexArray = null;

            // 重新绑定表格
            BindGrid2();
        }


        protected void Grid2_RowCommand(object sender, GridCommandEventArgs e)
        {
            object[] values = Grid2.DataKeys[e.RowIndex];
            int id = Convert.ToInt32(values[0]);

            if (e.CommandName == "Delete")
            {
                // 在操作之前进行权限检查
                if (!CheckPowerDelete())
                {
                    CheckPowerFailWithAlert();
                    return;
                }

                TblMstUser user = TblMstUser.FetchByID(id);
                user.RoleId = null;
                user.Save();

                BindGrid2();

            }
        }

        protected void Window1_Close(object sender, EventArgs e)
        {
            BindGrid2();
        }

        protected void btnNew_Click(object sender, EventArgs e)
        {
            List<int> ids = GetSelectedDataKeyIDs(Grid1);
            string addUrl = String.Format("~/admin/role_user_addnew.aspx?id={0}", ids[0]);

            PageContext.RegisterStartupScript(Window1.GetShowReference(addUrl, "添加用户到当前角色"));
        }

        #endregion

    }
}
